package br.com.classificadosonline.persistencia;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import br.com.classificadosonline.nucleo.Plano;

public class PlanoDAO {

	private static final PlanoDAO instance = null;

	public static PlanoDAO getInstance()
	{
		if (instance == null)
		{
			instance = new PlanoDAO();
		}
		return instance;
	}

	public static PlanoDAO obterInstancia() {
		return (PlanoDAO) Conexao.select("SELECT * FROM PLANO");
	}
	
	public static void cadastrarPlano(Float valor, String nome, int dias) {
		Conexao.update("INSERT INTO PLANO VALUES (" + valor + ", '" + nome + "'," + dias + ")");
	}
	
	public static void modificarPlano(int codigo, Float valor, String nome, int dias) {
		Conexao.update("UPDATE PLANO SET VALOR=" + valor + ", NOME='" + nome + "', DIAS=" + dias + " WHERE CODIGO=" + codigo);
	}	
	
	public static Plano buscarPlano(int codigo) {
		return buscar("SELECT * FROM PLANO WHERE CODIGO=" + codigo).get(0);
	}
	
	public static List<Plano> buscar(String query) {
		ResultSet rs = null;
		List<Plano> lista = new ArrayList<Plano>();
		Plano plano = null;	
		Statement stmt;
		try {
			stmt = Conexao.conexao().createStatement();							
			rs = stmt.executeQuery(query);
			while (rs.next()) {
				plano = new Plano(rs.getInt("CODIGO"), rs.getFloat("VALOR"), rs.getString("NOME"), rs.getInt("DIAS"));				
				lista.add(plano);
			}
			stmt.close();
			Conexao.conexao().close();	
		} catch (SQLException e) {
		}
		return lista;
	}
	
	public static List<Plano> listarPlano() {
		return buscar("SELECT * FROM PLANO");
	}
	
	public static void excluirPlano(int codigo) {
		Conexao.update("DELETE FROM PLANO WHERE CODIGO=" + codigo);
	}
}
